/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ejercicio.practica7;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;

/**
 *
 * @author manolo
 */
public class FicheroSeguro implements Runnable {

    private static RandomAccessFile fichero;

    public synchronized void escribir() {
        try {
            fichero.writeBytes(Thread.currentThread().getName() + ", escribiendo.\n");
            fichero.writeBytes(Thread.currentThread().getName() + ", finalizando.\n");
        } catch (IOException ex) {
            System.out.println("Error: " + ex);
        }
    }

    @Override
    public void run() {
        escribir();
    }

    public static void main(String[] args) throws FileNotFoundException, InterruptedException {
        String Dir = System.getProperty("user.dir");
        String nombreFichero;
        Scanner teclado = new Scanner(System.in);
        int nTareas = 10;

        System.out.println("Introduzca el nombre del fichero: ");
        nombreFichero = teclado.next();

        File archivo = new File(Dir + "/" + nombreFichero + ".txt");
        fichero = new RandomAccessFile(archivo, "rw");

        Thread[] Hilos = new Thread[nTareas];
        for (int i = 0; i < nTareas; ++i) {
            Hilos[i] = new Thread(new FicheroSeguro());
            Hilos[i].start();
        }
    }

}
